package com.nbcio.iot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nbcio.common.core.domain.R;
import com.nbcio.iot.domain.entity.IotDataPoint;
import com.nbcio.iot.domain.entity.IotDataRecord;
import com.nbcio.iot.domain.entity.IotDevice;
import com.nbcio.iot.mapper.IotDataPointMapper;
import com.nbcio.iot.mapper.IotDataRecordMapper;
import com.nbcio.iot.mapper.IotDeviceMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/iot/data")
@RequiredArgsConstructor
public class IotDataController {

    private final IotDeviceMapper deviceMapper;
    private final IotDataPointMapper pointMapper;
    private final IotDataRecordMapper recordMapper;

    @GetMapping("/records")
    public R<Page<IotDataRecord>> records(
            @RequestParam(required = false) Long deviceId,
            @RequestParam(required = false) String deviceCode,
            @RequestParam(required = false) String pointCode,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date beginTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime,
            @RequestParam(defaultValue = "1") long pageNum,
            @RequestParam(defaultValue = "10") long pageSize
    ) {
        Long resolvedDeviceId = deviceId;
        Long pointId = null;
        if (resolvedDeviceId == null && deviceCode != null && !deviceCode.isEmpty()) {
            if (deviceCode.matches("^\\d+$")) {
                try { resolvedDeviceId = Long.parseLong(deviceCode); } catch (NumberFormatException ignore) { }
            }
            if (resolvedDeviceId == null) {
                IotDevice d = deviceMapper.selectOne(new LambdaQueryWrapper<IotDevice>()
                        .eq(IotDevice::getDeviceCode, deviceCode).last("limit 1"));
                if (d != null) resolvedDeviceId = d.getDeviceId();
            }
        }
        if (resolvedDeviceId != null && pointCode != null && !pointCode.isEmpty()) {
            IotDataPoint p = pointMapper.selectOne(new LambdaQueryWrapper<IotDataPoint>()
                    .eq(IotDataPoint::getDeviceId, resolvedDeviceId)
                    .eq(IotDataPoint::getPointCode, pointCode).last("limit 1"));
            if (p != null) pointId = p.getPointId();
        }
        LambdaQueryWrapper<IotDataRecord> qw = new LambdaQueryWrapper<>();
        if (resolvedDeviceId != null) qw.eq(IotDataRecord::getDeviceId, resolvedDeviceId);
        if (pointId != null) qw.eq(IotDataRecord::getPointId, pointId);
        if (beginTime != null) qw.ge(IotDataRecord::getDataTime, beginTime);
        if (endTime != null) qw.le(IotDataRecord::getDataTime, endTime);
        qw.orderByDesc(IotDataRecord::getDataTime);

        log.info("[DATA-QUERY] deviceId={}, deviceCode={}, resolvedDeviceId={}, pointCode={}, beginTime={}, endTime={}, pageNum={}, pageSize={}",
                deviceId, deviceCode, resolvedDeviceId, pointCode, beginTime, endTime, pageNum, pageSize);

        Page<IotDataRecord> page = recordMapper.selectPage(new Page<>(pageNum, pageSize), qw);
        log.info("[DATA-QUERY] result total={}, currentPageRecords={}", page.getTotal(), page.getRecords() == null ? 0 : page.getRecords().size());
        return R.ok(page);
    }
} 